/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.common.util.encrypt.DESUtil
 * <p>
 * 类产生时间: 2014-09-16 14:40
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 项目组 : 苏州公安移动门户
 * <p>
 * 部门: 手持技术部
 * <p>
 * <p>
 */
package cn.com.oceansoft.nos.common.util.encrypt;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

/**
 * @author chenw
 * @time 2014-09-16 14:40
 */
public class DESUtil {

    private static Key key;
    private static String KEY_STR = "ZXCVBNM<>?'+_)(*&^%$#@!qa";// 密钥
    private static String CHARSETNAME = "UTF-8";// 编码
    private static String ALGORITHM = "DES";// 加密类型

    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            generator.init(new SecureRandom(KEY_STR.getBytes()));
            key = generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对str进行DES加密
     *
     * @param source 加密字符串源
     * @return 密文字符串
     */
    public static String encrypt(String source) {
        BASE64Encoder base64encoder = new BASE64Encoder();
        try {
            byte[] bytes = source.getBytes(CHARSETNAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return base64encoder.encode(doFinal);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对str进行DES解密
     *
     * @param source 待解密字符串
     * @return 明文字符串
     */
    public static String decrypt(String source) {
        BASE64Decoder base64decoder = new BASE64Decoder();
        try {
            byte[] bytes = base64decoder.decodeBuffer(source);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSETNAME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        //SR2BbI8LLvQoZWbBw2K8HLAY53pfwDwEEmVan6BhAdYrBCFpsTOFSA==
        String str = encrypt("jdbc:oracle:thin:@172.17.100.139:1521:orcl");
        str = "bG2lwDOHSFGg1qC02sJ+GE3U30+QbUAaH7sIiM8/Fpw7ZUhW6LTL5yO4w15sYsxA";
        System.out.println("target=" + str);
        System.out.println("decrypt=" + decrypt(str));
    }
}
